<?php

# 运行目录
define('RUNTIME_DIR_ROOT',   dirname(__FILE__));


require_once 'conf/config.php';

$JSON_IO      = false;
$JSONP        = false;
$DIE_ON_ERROR = true;
$ARGS         = array();
$METHOD       = array();

$_RG = array();

date_default_timezone_set("Asia/Shanghai");

spl_autoload_register('lx_autoload');

chdir(RUNTIME_DIR_ROOT);

session_start();

function lx_method($name){
    $file = RUNTIME_DIR_METHOD . "$name.php";
    if(file_exists($file)){
        return $file;
    }
    $path = explode('.', $name);
    $n    = count($path) - 1;
    if($n < 1){
        return RUNTIME_METHOD_NOTFOUND;
    }
    $i = 1;
    $dir  = RUNTIME_DIR_METHOD . $path[0];
    while($i < $n && file_exists($dir)){
        $dir .= "/" . $path[++$i];
    }
    $file = "$dir/{$path[$n]}.php";
    if(file_exists($file)){
        return $file;
    }
    return RUNTIME_METHOD_NOTFOUND;
}

function lx_autoload($class_name){
    $file = RUNTIME_DIR_CLASS . "$class_name.class.php";
    if(file_exists($file)){
        include_once($file);
    }else if(FORCE_AUTOLOAD){
        if(!in_array($class_name, array('IO', 'DB'))){
            IO::e(-1, "Class '$class_name' not exist!");
        }
        // header(IO_HEAD);
        if(defined('IO_JSON')){
            die(
                json_encode(
                    array(
                        'code'    =>0, 
                        'message' => "Core class '$class_name' not exist!"
                    )
                )
            );
        }else{
            die("Core class '$class_name' not exist!");
        }
    }
}

function lx_logic($class_name, $func){
    $file = RUNTIME_DIR_CLASS . "logic/$class_name.class.php";
    if(!file_exists($file)){
        return false;
    }
    include_once($file);
    $obj = new $class_name;
    if(!method_exists($obj, $func)){
        return false;
    }
    $obj->$func();
    return $obj;
}

function lx_stack_trace(){
    $stack = debug_backtrace();
    foreach($stack as $r){
        echo '----', $r['file'], ', <b>line</b>', $r['line'], ', <b>function</b>:', $r['function']."<br />";
    }
}

function lx_plugin_config($plugin_name){
    $file = "conf/plugin/$plugin_name.php";
    if(!file_exists($file)){
        IO::e(-1, "Plugin configuration '$plugin_name' not exist!");
    }
    include_once $file;
    $class_name = "config_plugin_$plugin_name";
    $config_class = new $class_name;
    return $config_class->get_config();
}
